package wiki.mdzz.learn_android.utils

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast

class DatabaseHelper(val context: Context, name: String, version: Int) :
    SQLiteOpenHelper(context, name, null, version) {

//  private val dropBook = "drop table if exists Book;"
  private val createBook =
      "create table book (id integer primary key autoincrement, author text, price real, pages integer, name text);"

  private val createCategory =
      "create table category (id integer primary key autoincrement, name text, code integer)"

  override fun onCreate(db: SQLiteDatabase?) {
    if (db != null) {
      db.execSQL(createBook)
      db.execSQL(createCategory)
      Toast.makeText(context, "Create succeed", Toast.LENGTH_SHORT).show()
    }
  }

  override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    if (oldVersion <= 1) {
      db?.execSQL(createCategory)
    }
    if (oldVersion <= 2) {
      db?.execSQL("alter table book add column category_id integer")
    }
  }
}
